<?php
/**
 * Created by PhpStorm.
 * User: huxiuchang
 * Date: 15-9-17
 * Time: 下午1:50
 */
class BaseController
{
    protected $view;

    public function __construct()
    {
    }

    public function __destruct()
    {
        //视图模块
        // $view = $this->view;
        // if ( $view instanceof View ) {
        //     extract($view->data);
        //     require $view->view;
        // }

        //邮件发送模块
        // $mail = $this->mail;
        // if ( $mail instanceof Mail ) {
        //     $mailer = new Nette\Mail\SmtpMailer($mail->config);
        //     $mailer->send($mail);
        // }
    }

    //生成token
    public static function setToken($user)
    {
         //生成一个不会重复的字符串
        $str = md5(uniqid(md5(microtime(true)),true)); 

        //加密
        $access_token = sha1($str);

        $expires_at = time() + $user->apiTimeout;

        //存入redis
        RedisCache::set($access_token, serialize($user), $user->apiTimeout, 's');
        $res['access_token'] = $access_token;
        $res['expires_at'] = $expires_at;
        return $res;
    }


    //token验证方法，如果12小时没被调用则需要重新授权
    public static function checkToken($access_token)
    {
        $redis_token = RedisCache::get($access_token);
        if ($redis_token)
        {
            return true;
        } else {
            $res['success'] = false;
            $res['desc'] = 'token_expired';
            echo json_encode($res, JSON_UNESCAPED_UNICODE);
            exit();
        }
    }

    public static function verifyPassword($username, $aes_password, $hash, $user_id = 0)
    {
        $password = self::aesDecode($aes_password, $username, true);
        $match = false;
        $match = password_verify($password, $hash);
        return $match;
    }

    /**
     * 路径安全base64编码
     * @method base64Encode
     * @param  string       $str [编码前字符串]
     * @return string                  [编码后字符串]
     * @author NewFuture
     */
    public static function base64Encode($str)
    {
        return strtr(base64_encode($str), array('+' => '-', '=' => '_', '/' => '.'));
    }

    /**
     * 路径安全形base64解码
     * @method base64Decode
     * @param  string      $tr [解码前字符串]
     * @return string           [解码后字符串]
     * @author NewFuture
     */
    public static function base64Decode($str)
    {
        return base64_decode(strtr($str, array('-' => '+', '_' => '=', '.' => '/')));
    }

    /**
     * aes_encode(&$data, $key)
     *  aes加密函数,$data引用传真，直接变成密码
     *  采用mcrypt扩展,为保证一致性,初始向量设为0
     * @param &$data 原文
     * @param $key 密钥
     * @return string(16) 加密后的密文
     */
    public static function aesEncode($data, $key, $safe_view = false)
    {
        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
        mcrypt_generic_init($td, $key, '0000000000000000');
        $data = mcrypt_generic($td, $data);
        mcrypt_generic_deinit($td);
        return $safe_view ? self::base64Encode($data) : $data;
    }

    /**
     * aes_decode(&$cipher, $key)
     *  aes解密函数,$cipher引用传真也会改变
     * @param &$cipher 密文
     * @param $key 密钥
     * @return string 解密后的明文
     */
    public static function aesDecode($cipher, $key, $safe_view = false)
    {
        if ($cipher)
        {
            $safe_view AND $cipher = self::base64Decode($cipher);

            $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
            mcrypt_generic_init($td, $key, '0000000000000000');
            $cipher = mdecrypt_generic($td, $cipher);
            mcrypt_generic_deinit($td);
            $cipher = trim($cipher);
            return $cipher;
        }
    }

    /**
     * 该函数返回一个自定义长度的随机数
     *
     * 参数：
     *       $length 需要返回随机数的长度.如果$length大于随机种子的长度，那么系统将会自动使用随机种子的长度
     *       $pattern
                    随机种子，如果需要产地特定的字符串的随机数，那么可以设置$pattern 
                    $pattern 默认为 null  也就是采用系统的随机种子
                    $pattern = "1234567890abcdefghijklmnopqrstuvwxyz";  
     *           
     * 返回：$key  随机字符串
     *  
     *   ##### 注意 $length的长度是有限制的
     *     
     */
   static public function makeRandomNum($length ,$pattern = null)
   {
        if($pattern == null)
        {
            $pattern = "1234567890abcdefghijklmnopqrstuvwxyz";
        }
        $maxLength = strlen($pattern);
        $length = $length < $maxLength?$length:$maxLength;
        $key="";
        for($i=0;$i<$length;$i++)
        {
            $key .= $pattern{rand(0,$length)};
        }
        return $key;
   }

   static public function newOrderNo()
    {
        $strfirstRandom =self::makeRandomNum(4); 
        $strTime = strval(time());
        $strLastRandom = self::makeRandomNum(4);
        $strOrderNum = $strfirstRandom.$strTime.$strLastRandom;
        return $strOrderNum;
    }

    static public function replacePicUrl($content = null, $strUrl = null) {  
    if ($strUrl) {  
        //提取图片路径的src的正则表达式 并把结果存入$matches中    
        preg_match_all("/<img(.*)src=\"([^\"]+)\"[^>]+>/isU",$content,$matches);  
        $img = "";    
        if(!empty($matches)) {    
        //注意，上面的正则表达式说明src的值是放在数组的第三个中    
        $img = $matches[2];    
        }else {    
           $img = "";    
        }  
          if (!empty($img)) {    
                $patterns= array();    
                $replacements = array();    
                foreach($img as $imgItem){    
                    $final_imgUrl = $strUrl.$imgItem;    
                    $replacements[] = $final_imgUrl;    
                    $img_new = "/".preg_replace("/\//i","\/",$imgItem)."/";    
                    $patterns[] = $img_new;    
                }    
    
                //让数组按照key来排序    
                ksort($patterns);    
                ksort($replacements);    
    
                //替换内容    
                $vote_content = preg_replace($patterns, $replacements, $content);  
          
                return $vote_content;  
        }else {  
            return $content;  
        }                     
    } else {  
        return $content;  
    }  
}  
    
}